package chatin.mediator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UsersAccount {

	private String user;

	private Connection connection;

	public UsersAccount() {
		this.connection = ConnectionsGuardian.getConnectionsGuardian()
				.getConnection();
	}

	public boolean login(String username, String password) {

		boolean flag = false;

		try {
			String sql = "SELECT usuario, senha, nome, nivel from usuarios WHERE usuario=? AND senha=?;";

			PreparedStatement pstm = this.connection.prepareStatement(sql);
			pstm.setString(1, username);
			pstm.setString(2, password);
			ResultSet rs = pstm.executeQuery();
			flag = rs.next();

			if (flag) {
				System.out.println(rs.getString("nome"));
				// atualiza mapa de usuários do mediador
				MapsGuardian.getMapsGuardian().addUser(username,
						"http://127.0.0.1:8080/xmlrpc");
				MapsGuardian.getMapsGuardian().showUsers();
			}

		} catch (SQLException eAuth) {
			System.out.println("Houve erro na autenticação do usuario");
			eAuth.printStackTrace();
		}

		return flag;
	}

	public void logout(String username) {
		MapsGuardian.getMapsGuardian().removeUser(username);
	}

	public String getUsername() {
		return user;
	}
}
